<?php

namespace app\db\admin;

use ltcms\db\Db_raw;

class D_adManage
{
    /**
     * 信息格式化
     */
    private function detailed($Result, $format)
    {
        // 广告类型
        if (isset($Result['type'])) {
            $statusMap = array();
            $statusMap["1"] = "图片";
            $statusMap["2"] = "文字";
            $statusMap["3"] = "代码";
            $Result['typeFormat'] = isset($statusMap[$Result['type']]) ? $statusMap[$Result['type']] : "未知类型" . $Result['type'];
        }
        // 开始时间
        if (isset($Result['startTime'])) {
            $Result['startTimeFormat'] = $Result['startTime'] == 0 ? "不限" : app("ltcmsTime")::getDateTime('Y-m-d H:i:s', $Result['startTime']);
        }
        // 结束时间
        if (isset($Result['endTime'])) {
            $Result['endTimeFormat'] = $Result['endTime'] == 0 ? "不限" : app("ltcmsTime")::getDateTime('Y-m-d H:i:s', $Result['endTime']);
        }
        // 返回结果
        return $Result;
    }

    /**
     * 获取数据详情
     * @param string $paramObj
     */
    public function info($paramObj = "")
    {
        $dataObj = paramsObj();
        $dataObj->request = paramsObj();
        $dataObj->data = paramsObj();
        $dataObj->data->use_trans = false;
        $dataObj->result = new \ArrayObject();

        $final_arr = logInit();
        if ($final_arr["error_no"] == 0) {
            $mixed = parseToArr($paramObj, "mixed", 0);
            $params = parseToArr($paramObj, "params", array());
            $messages = parseToArr($paramObj, "messages", array());
            $rules = array(
                'id' => 'require|integer|gt:0',
                'field' => '',
                'verify' => '',
            );
            $dataDefault["verify"] = 1;
            $dataDefault["field"] = "*";
            $paramsObj = paramsObj();
            $paramsObj->params = $params;
            $paramsObj->mixed = $mixed;
            $paramsObj->rules = $rules;
            $paramsObj->messages = $messages;
            $paramsObj->dataDefault = $dataDefault;
            $checkResult = app("verifyParam")::validatorRequest($paramsObj);
            if ($checkResult["error_no"] == 0) {
                $dataObj->request = $checkResult["result"];
            } else {
                $final_arr = logCallErrorMsg($final_arr, $checkResult);
            }
        }
        if ($final_arr["error_no"] == 0) {
            $condition = array();
            $condition[] = array(
                "id", "=", $dataObj->request->id
            );
            try {
                $result = Db()->name(app("cmsTable")::adManage())->where($condition)->find();
                if ($dataObj->request->verify) {
                    if (empty($result)) {
                        $final_arr = recordLogMsgLevelTwo(app("errorLevel")::E_WARNING, app("errorCode")::DATA_NOT_EXIST, lang("sys.dataNotExists"));
                    }
                }
                if ($final_arr["error_no"] == 0 && $result) {
                    $final_arr["result"] = $result;
                }
            } catch (\Throwable $e) {
                $final_arr = recordLogMsgLevelTwo(app("errorLevel")::E_ERROR, app("errorCode")::SQL_ERROR, lang("sys.error"), $e->getMessage());
            }
        }
        return $final_arr;
    }

    /**
     * 创建数据
     * @param string $paramObj
     */
    public function store($paramObj = "")
    {
        $dataObj = paramsObj();
        $dataObj->request = paramsObj();
        $dataObj->data = paramsObj();
        $dataObj->data->use_trans = false;
        $dataObj->result = new \ArrayObject();

        $final_arr = logInit();
        if ($final_arr["error_no"] == 0) {
            $mixed = parseToArr($paramObj, "mixed", 0);
            $params = parseToArr($paramObj, "params", array());
            $messages = parseToArr($paramObj, "messages", array());
            $rules = array(
                'type' => 'require|number',
                'positionId' => 'require|number',
                'content' => '',
                'name' => '',
                'link' => 'url',
                'sortWeights' => '',
                'startTime' => '',
                'endTime' => '',
                'description' => '',
                'content1' => '',
                'content2' => '',
                'content3' => '',
            );
            $dataDefault = array(
                "sortWeights" => self::getSortWeightsMax() + 1,
            );
            $paramsObj = paramsObj();
            $paramsObj->params = $params;
            $paramsObj->mixed = $mixed;
            $paramsObj->rules = $rules;
            $paramsObj->messages = $messages;
            $paramsObj->dataDefault = $dataDefault;
            $checkResult = app("verifyParam")::validatorRequest($paramsObj);
            if ($checkResult["error_no"] == 0) {
                $dataObj->request = $checkResult["result"];
            } else {
                $final_arr = logCallErrorMsg($final_arr, $checkResult);
            }
        }
        if ($final_arr["error_no"] == 0) {
            try {
                $data = array();
                $data["type"] = $dataObj->request->type;
                $data["positionId"] = $dataObj->request->positionId;
                $data["sortWeights"] = $dataObj->request->sortWeights;
                $data["content"] = "";

                if (isset($dataObj->request->link)) {
                    $data["link"] = $dataObj->request->link;
                }
                if (isset($dataObj->request->name)) {
                    $data["name"] = $dataObj->request->name;
                }
                if ($dataObj->request->startTime) {
                    $data["startTime"] = app("ltcmsTime")::getTime($dataObj->request->startTime);
                }
                if ($dataObj->request->endTime) {
                    $data["endTime"] = app("ltcmsTime")::getTime($dataObj->request->endTime);
                }
                if (isset($dataObj->request->description)) {
                    $data["description"] = $dataObj->request->description;
                }

                if ($dataObj->request->type) {  //null 或空
                    switch ($dataObj->request->type) {
                        case 1:
                            if ($dataObj->request->content1) {  //null 或空
                                $data["content"] = $dataObj->request->content1;
                            }
                            break;
                        case 2:
                            if ($dataObj->request->content2) {  //null 或空
                                $data["content"] = $dataObj->request->content2;
                            }
                            break;
                        case 3:
                            if ($dataObj->request->content3) {  //null 或空
                                $data["content"] = $dataObj->request->content3;
                            }
                            break;
                    }
                }


                $result = Db()->name(app("cmsTable")::adManage())->insert($data);
                $return = array();
                $return["id"] = $result["insert_id"];
                $return["affected_rows"] = $result["affected_rows"];
                $final_arr["result"] = $return;
            } catch (\Throwable $e) {
                $final_arr = recordLogMsgLevelTwo(app("errorLevel")::E_ERROR, app("errorCode")::SQL_ERROR, lang("sys.error"), $e->getMessage());
            }
        }
        return $final_arr;
    }

    /**
     * 更新数据
     * @param string $paramObj
     */
    public function update($paramObj = "")
    {
        $dataObj = paramsObj();
        $dataObj->request = paramsObj();
        $dataObj->data = paramsObj();
        $dataObj->data->use_trans = false;
        $dataObj->result = new \ArrayObject();

        $final_arr = logInit();
        if ($final_arr["error_no"] == 0) {
            $mixed = parseToArr($paramObj, "mixed", 0);
            $params = parseToArr($paramObj, "params", array());
            $messages = parseToArr($paramObj, "messages", array());
            $rules = array(
                'id' => 'require|number',
                'name' => '',
                'type' => 'number',
                'positionId' => 'number',
                'link' => 'url',
                'sortWeights' => '',
                'startTime' => '',
                'endTime' => '',
                'content' => '',
                'content1' => '',
                'content2' => '',
                'content3' => '',
                'description' => '',
                'verify' => '',
            );
            $dataDefault = array();
            $dataDefault["verify"] = 1;
            $paramsObj = paramsObj();
            $paramsObj->params = $params;
            $paramsObj->mixed = $mixed;
            $paramsObj->rules = $rules;
            $paramsObj->messages = $messages;
            $paramsObj->dataDefault = $dataDefault;
            $checkResult = app("verifyParam")::validatorRequest($paramsObj);
            if ($checkResult["error_no"] == 0) {
                $dataObj->request = $checkResult["result"];
            } else {
                $final_arr = logCallErrorMsg($final_arr, $checkResult);
            }
        }
        if ($final_arr["error_no"] == 0) {
            if ($dataObj->request->verify) {
                $paramsObj = paramsObj();
                $paramsObj->params = array(
                    "id" => $dataObj->request->id,
                );
                $checkResult = $this->info($paramsObj);
                if ($checkResult["error_no"] == 0) {

                } else {
                    $final_arr = logCallErrorMsg($final_arr, $checkResult);
                }
            }
        }
        if ($final_arr["error_no"] == 0) {
            $condition = array();
            $condition[] = array(
                "id", "=", $dataObj->request->id
            );
            $data = array();
            $allowUpdates = ["name", "type", "positionId", "link", "sortWeights", "content", "description"]; //允许更新的字段
            foreach ($dataObj->request as $key => $value) {
                if (in_array($key, $allowUpdates)  && $value !== null) {


                    $data[$key] = $value;
                }
            }
            if (isset($dataObj->request->startTime)) {
                if (is_int($dataObj->request->startTime)) {
                    $data["startTime"] = $dataObj->request->startTime;
                } else if (strlen($dataObj->request->startTime) == 10 || strlen($dataObj->request->startTime) == 0) {
                    $data["startTime"] = intval($dataObj->request->startTime);
                } else {
                    $data["startTime"] = app("ltcmsTime")::getTime($dataObj->request->startTime);
                }
            }

            if (isset($dataObj->request->endTime)) {
                if (is_int($dataObj->request->endTime)) {
                    $data["endTime"] = $dataObj->request->endTime;
                } else if (strlen($dataObj->request->endTime) == 10 || strlen($dataObj->request->endTime) == 0) {
                    $data["endTime"] = intval($dataObj->request->endTime);
                } else {
                    $data["endTime"] = app("ltcmsTime")::getTime($dataObj->request->endTime);
                }
            }
            if ($dataObj->request->type) {  //null 或空
                switch ($dataObj->request->type) {
                    case 1:
                        if ($dataObj->request->content1) {  //null 或空
                            $data["content"] = $dataObj->request->content1;
                        }
                        break;
                    case 2:
                        if ($dataObj->request->content2) {  //null 或空
                            $data["content"] = $dataObj->request->content2;
                        }
                        break;
                    case 3:
                        if ($dataObj->request->content3) {  //null 或空
                            $data["content"] = $dataObj->request->content3;
                        }
                        break;
                }
            }


            if ($data) {
                try {
                    $result = Db()->name(app("cmsTable")::adManage())->where($condition)->data($data)->update();
                    $return = array();
                    $return["id"] = $dataObj->request->id;
                    $return["affected_rows"] = $result["affected_rows"];
                    $final_arr["result"] = $return;
                } catch (\Throwable $e) {
                    $final_arr = recordLogMsgLevelTwo(app("errorLevel")::E_ERROR, app("errorCode")::SQL_ERROR, lang("sys.error"), $e->getMessage());
                }
            } else {
                $return = array();
                $return["id"] = $dataObj->request->id;
                $return["affected_rows"] = 0;
                $final_arr["result"] = $return;
            }
        }
        return $final_arr;
    }


    /**
     * 删除数据
     * @param string $paramObj
     */
    public function delete($paramObj = "")
    {
        $dataObj = paramsObj();
        $dataObj->request = paramsObj();
        $dataObj->data = paramsObj();
        $dataObj->data->use_trans = false;
        $dataObj->result = new \ArrayObject();

        $final_arr = logInit();
        if ($final_arr["error_no"] == 0) {
            $mixed = parseToArr($paramObj, "mixed", 0);
            $params = parseToArr($paramObj, "params", array());
            $messages = parseToArr($paramObj, "messages", array());
            $rules = array(
                'id' => 'require',
            );
            $dataDefault = array();
            $paramsObj = paramsObj();
            $paramsObj->params = $params;
            $paramsObj->mixed = $mixed;
            $paramsObj->rules = $rules;
            $paramsObj->messages = $messages;
            $paramsObj->dataDefault = $dataDefault;
            $checkResult = app("verifyParam")::validatorRequest($paramsObj);
            if ($checkResult["error_no"] == 0) {
                $dataObj->request = $checkResult["result"];
            } else {
                $final_arr = logCallErrorMsg($final_arr, $checkResult);
            }
        }
        if ($final_arr["error_no"] == 0) {
            $ids = is_array($dataObj->request->id) ? $dataObj->request->id : explode(",", $dataObj->request->id);
            $condition = array();
            $condition[] = array(
                "id", "in", $ids
            );
            try {
                $result = Db()->name(app("cmsTable")::adManage())->where($condition)->delete();
                $return = array();
                $return["affected_rows"] = $result["affected_rows"];
                $final_arr["result"] = $return;
            } catch (\Throwable $e) {
                $final_arr = recordLogMsgLevelTwo(app("errorLevel")::E_ERROR, app("errorCode")::SQL_ERROR, lang("sys.error"), $e->getMessage());
            }
        }
        return $final_arr;
    }

    /**
     * 列表数据
     * @param string $paramObj
     */
    public function listData($paramObj = "")
    {
        $dataObj = paramsObj();
        $dataObj->request = paramsObj();
        $dataObj->data = paramsObj();
        $dataObj->data->use_trans = false;
        $dataObj->result = array();

        $final_arr = logInit();
        if ($final_arr["error_no"] == 0) {
            $mixed = parseToArr($paramObj, "mixed", 0);
            $params = parseToArr($paramObj, "params", array());
            $messages = parseToArr($paramObj, "messages", array());
            $rules = array(
                'order' => '',
                'positionId' => '',
                'name' => '',
                'field' => '',
                'format' => '',
            );
            $dataDefault = array(
                'order' => '0',
            );
            $dataDefault["field"] = "*";
            $dataDefault["format"] = "1";
            $paramsObj = paramsObj();
            $paramsObj->params = $params;
            $paramsObj->mixed = $mixed;
            $paramsObj->rules = $rules;
            $paramsObj->messages = $messages;
            $paramsObj->dataDefault = $dataDefault;
            $checkResult = app("verifyParam")::validatorRequest($paramsObj);
            if ($checkResult["error_no"] == 0) {
                $dataObj->request = $checkResult["result"];
            } else {
                $final_arr = logCallErrorMsg($final_arr, $checkResult);
            }
        }
        if ($final_arr["error_no"] == 0) {
            $condition = array();
            if ($dataObj->request->name) {
                $raw=new Db_raw();
                $raw->setContent("LOCATE('{$dataObj->request->name}',`name`)");
                $condition[] = array(
                    $raw, ">", 0
                );
            }
            if ($dataObj->request->positionId) {
                $condition[] = array(
                    "positionId", "=", $dataObj->request->positionId
                );
            }
            //处理 排序  设置默认0
            $sortColumn = "id";
            $sortDirection = $dataObj->request->order % 2 === 1 ? "ASC" : "DESC";   //单数升序 双数降序 0也为降序

            switch ($dataObj->request->order) {
                case 1:
                case 2:  // id 升序
                    $sortColumn = "id";
                    break;
            }

            try {
                $result = Db()->name(app("cmsTable")::adManage())->order($sortColumn, $sortDirection)->field($dataObj->request->field)->where($condition)->paginate();
                if ($result && $result["data"]) {
                    foreach ($result["data"] as $key => $val) {
                        if ($dataObj->request->format) {
                            $result["data"][$key] = $this->detailed($val, $dataObj->request->format);
                        }
                    }
                }
                $final_arr["result"] = $result;
            } catch (\Throwable $e) {
                $final_arr = recordLogMsgLevelTwo(app("errorLevel")::E_ERROR, app("errorCode")::SQL_ERROR, lang("sys.error"), $e->getMessage());
            }
        }
        return $final_arr;
    }

    //获取排序权重最大值
    private function getSortWeightsMax(): int
    {
        try {
            $tbPre = app("cmsTable")::adManage();
            $sql = "SELECT MAX(sortWeights) as MAX FROM {$tbPre}  ";
            $result = Db()->find($sql);
        } catch (\Throwable $e) {
            //内部使用,失败直接返回0
            return 0;
        }
        return $result["MAX"] ? $result["MAX"] : 0;   //第一次添加可能为 null
    }

    public function __call($name, $arguments)
    {
        return recordLogMsgLevelTwo(app("errorLevel")::E_WARNING, app("errorCode")::UNDEFINED_METHOD, lang("sys.noMethodDefined"), $name, $arguments);
    }
}